package com.xhj.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.OSSObject;
import com.xhj.config.OSSProperties;
import com.xhj.service.OSSService;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
@Slf4j
public class OSSServiceImpl implements OSSService {

    @Autowired
    private OSSProperties ossProperties;

    @Override
    public String uploadFile(MultipartFile file) {
        /*
         * Constructs a client instance with your account for accessing OSS
         */
        String endpoint = ossProperties.getEndpoint();
        String bucketName = ossProperties.getBucketName();
        String accessKeyId = ossProperties.getAccessKeyId();
        String accessKeySecret = ossProperties.getAccessKeySecret();
        String fileHost = ossProperties.getFileHost();
        OSS client = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 设置存储空间的访问权限为：公共读。
        client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
        try {
            /*
             * Create an empty folder without request body, note that the key must be
             * suffixed with a slash
             */
            InputStream inputStream = file.getInputStream();
            // 构建日期路径：avatar/2021/02/24/文件名
            String filePath = new DateTime().toString("yyyy/MM/dd");
            // 构建uuid文件名
            String originalFilename = file.getOriginalFilename();
            String fileName = UUID.randomUUID().toString().replace("-","").toUpperCase();
            String fileType = originalFilename.substring(originalFilename.lastIndexOf("."));
            String uuidName = fileName + fileType;
            String uploadPath = filePath + "/" + uuidName;
            // 获得文件路径 https://bossxie.oss-cn-guangzhou.aliyuncs.com/xhj/avatar/%E8%9F%B9%E8%80%81%E6%9D%BF%E5%A4%B4%E5%83%8F.jpg
            String fileUrl = fileHost + "/" + uploadPath;

            client.putObject(bucketName, uploadPath, inputStream);
//            System.out.println("Creating an empty folder " + keySuffixWithSlash + "\n");

            /*
             * Verify whether the size of the empty folder is zero
             */
//            OSSObject object = client.getObject(bucketName, uuidName);
//            System.out.println("Size of the empty folder '" + object.getKey() + "' is " +
//                    object.getObjectMetadata().getContentLength());
//
//            object.getObjectContent().close();

            return fileUrl;

        }  catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        } finally {
            /*
             * Do not forget to shut down the client finally to release all allocated resources.
             */
            client.shutdown();
        }
    }
}
